// 渲染进程逻辑
// electronAPI 通过 preload 注入，无需 require('electron')

// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', () => {
  loadCases();

  const newCaseBtn = document.querySelector('.new-case-btn');
  const importCaseBtn = document.querySelector('.import-case-btn');

  if (newCaseBtn) {
    newCaseBtn.addEventListener('click', showNewCaseModal);
  }

  if (importCaseBtn) {
    importCaseBtn.addEventListener('click', showImportCaseModal);
  }

  const queryBtn = document.getElementById('queryBtn');
  const resetBtn = document.getElementById('resetBtn');

  if (queryBtn) {
    queryBtn.addEventListener('click', performSearch);
  }

  if (resetBtn) {
    resetBtn.addEventListener('click', resetSearch);
  }

  // Bind Enter key for search inputs
  ['searchCaseNumber', 'searchCaseName'].forEach(id => {
    const input = document.getElementById(id);
    if (input) {
      input.addEventListener('keypress', (e) => {
        if (e.key === 'Enter') performSearch();
      });
    }
  });

  // 绑定弹出层相关事件 - 只绑定一次
  bindModalEvents();
  bindEditModalEvents();
  bindExportModalEvents();
  bindImportModalEvents();
  bindPasswordModalEvents();  // 添加密码模态框事件绑定
  // 使用更精确的事件委托
  setupCardEventDelegation();

  // 点击文档其他地方关闭下拉菜单
  document.addEventListener('click', (e) => {
    if (!e.target.closest('.dropdown')) {
      const openMenus = document.querySelectorAll('.dropdown-menu.show');
      openMenus.forEach(menu => {
        menu.classList.remove('show');
        const card = menu.closest('.case-card');
        if (card) card.style.zIndex = '1';
      });
    }
  });

  // 模板管理链接点击事件 - 跳转到工作台的模板管理标签页
  const templateManageLink = document.getElementById('templateManageLink');
  if (templateManageLink) {
    templateManageLink.addEventListener('click', (e) => {
      e.preventDefault();
      // 使用 electronAPI 导航
      window.electronAPI.navigation.openWorkbench({ activeTab: 'template' });
    });
  }
});

// ========== 弹窗与焦点管理 ==========

// 隐藏模态框并强制重置焦点，解决输入框失效问题
function safeHideModal(modalId) {
  const modal = document.getElementById(modalId);
  if (modal) {
    modal.style.display = 'none';
    // 关键修复：强制让当前元素失去焦点，防止光标残留
    if (document.activeElement) {
      document.activeElement.blur();
    }
    // 将焦点交还给body或某个固定元素
    document.body.focus();
  }
}

// 绑定新增弹窗事件
function bindModalEvents() {
  const closeBtn = document.getElementById('closeNewCaseModal');
  const cancelBtn = document.getElementById('cancelNewCase');
  const newCaseForm = document.getElementById('newCaseForm');
  const modalOverlay = document.getElementById('newCaseModal');

  if (closeBtn && !closeBtn.hasAttribute('data-event-bound')) {
    closeBtn.addEventListener('click', hideNewCaseModal);
    closeBtn.setAttribute('data-event-bound', 'true');
  }

  if (cancelBtn && !cancelBtn.hasAttribute('data-event-bound')) {
    cancelBtn.addEventListener('click', hideNewCaseModal);
    cancelBtn.setAttribute('data-event-bound', 'true');
  }

  if (modalOverlay && !modalOverlay.hasAttribute('data-event-bound')) {
    modalOverlay.addEventListener('click', function (e) {
      if (e.target === modalOverlay) {
        hideNewCaseModal();
      }
    });
    modalOverlay.setAttribute('data-event-bound', 'true');
  }

  if (newCaseForm && !newCaseForm.hasAttribute('data-event-bound')) {
    newCaseForm.addEventListener('submit', handleNewCaseSubmit);
    newCaseForm.setAttribute('data-event-bound', 'true');
  }
}

// 显示新增案件弹出层
function showNewCaseModal() {
  const modal = document.getElementById('newCaseModal');
  if (modal) {
    resetNewCaseForm();
    generateCaseNumber();

    // 设置默认立案时间为当前日期
    const now = new Date();
    const year = now.getFullYear();
    const month = String(now.getMonth() + 1).padStart(2, '0');
    const day = String(now.getDate()).padStart(2, '0');
    document.getElementById('createTime').value = `${year}-${month}-${day}`;

    modal.style.display = 'flex';
    // 延迟聚焦，防止光标问题
    setTimeout(() => {
      const nameInput = document.getElementById('caseName');
      if (nameInput) nameInput.focus();
    }, 100);
  }
}

// 隐藏新增案件弹出层
function hideNewCaseModal() {
  safeHideModal('newCaseModal');
}

// 重置表单
function resetNewCaseForm() {
  const form = document.getElementById('newCaseForm');
  if (form) {
    form.reset();
    document.getElementById('caseDescription').value = '';
  }
}

// 生成案件编号
function generateCaseNumber() {
  const caseNumberInput = document.getElementById('caseNumber');
  if (caseNumberInput) {
    caseNumberInput.value = '系统自动生成';
  }
}

// 处理新增案件表单提交
async function handleNewCaseSubmit(event) {
  event.preventDefault();

  const formData = {
    case_name: document.getElementById('caseName').value,
    case_status: document.getElementById('caseCategory').value,
    created_time: document.getElementById('createTime').value,
    password: document.getElementById('casePassword').value,
    description: document.getElementById('caseDescription').value
  };

  if (!formData.case_name || !formData.case_status) {
    alert('请填写必填项');
    return;
  }

  const saveBtn = document.querySelector('#newCaseModal .btn-save');
  if (saveBtn && saveBtn.disabled) return;

  try {
    const originalText = saveBtn.textContent;
    saveBtn.textContent = '保存中...';
    saveBtn.disabled = true;

    await window.electronAPI.case.create({
      case_name: formData.case_name,
      case_status: formData.case_status,
      case_start_time: formData.created_time,
      password: formData.password,
      description: formData.description
    });

    // 不使用alert，优化体验
    saveBtn.textContent = '保存成功!';
    setTimeout(() => {
      hideNewCaseModal();
      loadCases();
      saveBtn.textContent = originalText;
      saveBtn.disabled = false;
    }, 500);

  } catch (error) {
    console.error('保存案件失败:', error);
    alert(`保存失败: ${error.message}`);
    if (saveBtn) {
      saveBtn.textContent = '保存';
      saveBtn.disabled = false;
    }
  }
}

// ========== 编辑功能 ==========

// 显示编辑案件弹出层
function showEditCaseModal(caseData) {
  const modal = document.getElementById('editCaseModal');
  if (modal) {
    document.getElementById('editCaseId').value = caseData.id;
    document.getElementById('editCaseNumber').value = caseData.case_number;
    document.getElementById('editCaseName').value = caseData.case_name;
    document.getElementById('editCaseCategory').value = caseData.case_status;

    // 只使用立案时间（case_start_time）
    const timeStr = caseData.case_start_time;
    if (timeStr) {
      const date = new Date(timeStr);
      if (!isNaN(date.getTime())) {
        // 对于日期输入，只需要年-月-日格式
        const year = date.getFullYear();
        const month = String(date.getMonth() + 1).padStart(2, '0');
        const day = String(date.getDate()).padStart(2, '0');
        document.getElementById('editStartTime').value = `${year}-${month}-${day}`;
      }
    }

    document.getElementById('editCaseDescription').value = caseData.description || '';
    modal.style.display = 'flex';

    // 强制启用输入框
    const inputs = modal.querySelectorAll('input, textarea, select');
    inputs.forEach(input => {
      input.disabled = false;
      input.readOnly = false;
      if (input.id === 'editCaseNumber') input.readOnly = true;
    });

    setTimeout(() => {
      const nameInput = document.getElementById('editCaseName');
      if (nameInput) nameInput.focus();
    }, 100);
  }
}

function hideEditCaseModal() {
  safeHideModal('editCaseModal');
}

function bindEditModalEvents() {
  const closeBtn = document.getElementById('closeEditCaseModal');
  const cancelBtn = document.getElementById('cancelEditCase');
  const editCaseForm = document.getElementById('editCaseForm');
  const modalOverlay = document.getElementById('editCaseModal');

  if (closeBtn && !closeBtn.hasAttribute('data-event-bound')) {
    closeBtn.addEventListener('click', function (e) {
      e.preventDefault();
      hideEditCaseModal();
    });
    closeBtn.setAttribute('data-event-bound', 'true');
  }

  if (cancelBtn && !cancelBtn.hasAttribute('data-event-bound')) {
    cancelBtn.addEventListener('click', function (e) {
      e.preventDefault();
      hideEditCaseModal();
    });
    cancelBtn.setAttribute('data-event-bound', 'true');
  }

  if (modalOverlay && !modalOverlay.hasAttribute('data-event-bound')) {
    modalOverlay.addEventListener('click', function (e) {
      if (e.target === modalOverlay) {
        hideEditCaseModal();
      }
    });
    modalOverlay.setAttribute('data-event-bound', 'true');
  }

  if (editCaseForm && !editCaseForm.hasAttribute('data-event-bound')) {
    editCaseForm.addEventListener('submit', handleEditCaseSubmit);
    editCaseForm.setAttribute('data-event-bound', 'true');
  }
}

// 绑定导出模态框事件
function bindExportModalEvents() {
  const closeBtn = document.getElementById('closeExportCaseModal');
  const cancelBtn = document.getElementById('cancelExportCase');
  const exportForm = document.getElementById('exportCaseForm');
  const modalOverlay = document.getElementById('exportCaseModal');
  const selectPathBtn = document.getElementById('selectExportPathBtn');
  const encryptPackage = document.getElementById('encryptPackage');

  if (closeBtn && !closeBtn.hasAttribute('data-event-bound-export')) {
    closeBtn.addEventListener('click', function (e) {
      e.preventDefault();
      hideExportCaseModal();
    });
    closeBtn.setAttribute('data-event-bound-export', 'true');
  }

  if (cancelBtn && !cancelBtn.hasAttribute('data-event-bound-export')) {
    cancelBtn.addEventListener('click', function (e) {
      e.preventDefault();
      hideExportCaseModal();
    });
    cancelBtn.setAttribute('data-event-bound-export', 'true');
  }

  if (modalOverlay && !modalOverlay.hasAttribute('data-event-bound-export')) {
    modalOverlay.addEventListener('click', function (e) {
      if (e.target === modalOverlay) {
        hideExportCaseModal();
      }
    });
    modalOverlay.setAttribute('data-event-bound-export', 'true');
  }

  if (exportForm && !exportForm.hasAttribute('data-event-bound-export')) {
    exportForm.addEventListener('submit', handleExportSubmit);
    exportForm.setAttribute('data-event-bound-export', 'true');
  }

  if (selectPathBtn && !selectPathBtn.hasAttribute('data-event-bound-export')) {
    selectPathBtn.addEventListener('click', selectExportPath);
    selectPathBtn.setAttribute('data-event-bound-export', 'true');
  }

  if (encryptPackage && !encryptPackage.hasAttribute('data-event-bound-export')) {
    encryptPackage.addEventListener('change', togglePasswordGroup);
    encryptPackage.setAttribute('data-event-bound-export', 'true');
  }
}

// 绑定导入模态框事件
function bindImportModalEvents() {
  const closeBtn = document.getElementById('closeImportCaseModal');
  const cancelBtn = document.getElementById('cancelImportCase');
  const importForm = document.getElementById('importCaseForm');
  const modalOverlay = document.getElementById('importCaseModal');
  const selectFileBtn = document.getElementById('selectImportFileBtn');

  if (closeBtn && !closeBtn.hasAttribute('data-event-bound-import')) {
    closeBtn.addEventListener('click', function (e) {
      e.preventDefault();
      hideImportCaseModal();
    });
    closeBtn.setAttribute('data-event-bound-import', 'true');
  }

  if (cancelBtn && !cancelBtn.hasAttribute('data-event-bound-import')) {
    cancelBtn.addEventListener('click', function (e) {
      e.preventDefault();
      hideImportCaseModal();
    });
    cancelBtn.setAttribute('data-event-bound-import', 'true');
  }

  if (modalOverlay && !modalOverlay.hasAttribute('data-event-bound-import')) {
    modalOverlay.addEventListener('click', function (e) {
      if (e.target === modalOverlay) {
        hideImportCaseModal();
      }
    });
    modalOverlay.setAttribute('data-event-bound-import', 'true');
  }

  if (importForm && !importForm.hasAttribute('data-event-bound-import')) {
    importForm.addEventListener('submit', handleImportSubmit);
    importForm.setAttribute('data-event-bound-import', 'true');
  }

  if (selectFileBtn && !selectFileBtn.hasAttribute('data-event-bound-import')) {
    selectFileBtn.addEventListener('click', selectImportFile);
    selectFileBtn.setAttribute('data-event-bound-import', 'true');
  }
}

// 处理编辑案件表单提交
async function handleEditCaseSubmit(event) {
  event.preventDefault();

  const formData = {
    id: parseInt(document.getElementById('editCaseId').value),
    case_name: document.getElementById('editCaseName').value,
    case_status: document.getElementById('editCaseCategory').value,
    description: document.getElementById('editCaseDescription').value,
    created_time: document.getElementById('editStartTime').value
  };

  if (!formData.case_name || !formData.case_status) {
    alert('请填写必填项');
    return;
  }

  const saveBtn = document.querySelector('#editCaseModal .btn-save');
  if (saveBtn && saveBtn.disabled) return;

  try {
    const originalText = saveBtn.textContent;
    saveBtn.textContent = '保存中...';
    saveBtn.disabled = true;

    await window.electronAPI.case.update({
      id: formData.id,
      case_name: formData.case_name,
      case_status: formData.case_status,
      description: formData.description,
      case_start_time: formData.created_time
    });

    saveBtn.textContent = '已更新';
    setTimeout(() => {
      hideEditCaseModal();
      loadCases();
      saveBtn.textContent = originalText;
      saveBtn.disabled = false;
    }, 500);
  } catch (error) {
    console.error('更新案件失败:', error);
    saveBtn.textContent = '更新失败';
    setTimeout(() => {
      saveBtn.textContent = originalText;
      saveBtn.disabled = false;
    }, 1000);
  }
}

// ========== 列表与卡片展示 ==========

async function loadCases(filters = {}) {
  const casesGrid = document.getElementById('casesGrid');
  casesGrid.innerHTML = '<div style="text-align:center; padding:20px; color:#909399;">加载中...</div>';

  try {
    let cases = await window.electronAPI.case.getAll();

    // 前端筛选逻辑
    if (filters.caseNumber) {
      cases = cases.filter(c => c.case_number && c.case_number.includes(filters.caseNumber));
    }
    if (filters.caseName) {
      cases = cases.filter(c => c.case_name && c.case_name.includes(filters.caseName));
    }
    if (filters.startDate) {
      const start = new Date(filters.startDate).getTime();
      cases = cases.filter(c => {
        // 使用立案时间(case_start_time)进行筛选，如果没有立案时间则使用创建时间
        const timeStr = c.case_start_time || c.created_time;
        const time = new Date(timeStr).getTime();
        return time >= start;
      });
    }
    if (filters.endDate) {
      // End date should be inclusive, so add 1 day or set to end of day
      const end = new Date(filters.endDate).getTime() + 86400000;
      cases = cases.filter(c => {
        // 使用立案时间(case_start_time)进行筛选，如果没有立案时间则使用创建时间
        const timeStr = c.case_start_time || c.created_time;
        const time = new Date(timeStr).getTime();
        return time < end;
      });
    }

    displayCases(cases);
  } catch (error) {
    console.error('加载案件数据失败:', error);
    casesGrid.innerHTML = '<p style="text-align: center; color: #f56c6c;">加载失败</p>';
  }
}

function performSearch() {
  const filters = {
    caseNumber: document.getElementById('searchCaseNumber').value.trim(),
    caseName: document.getElementById('searchCaseName').value.trim(),
    startDate: document.getElementById('searchStartDate').value,
    endDate: document.getElementById('searchEndDate').value
  };
  loadCases(filters);
}

function resetSearch() {
  document.getElementById('searchCaseNumber').value = '';
  document.getElementById('searchCaseName').value = '';
  document.getElementById('searchStartDate').value = '';
  document.getElementById('searchEndDate').value = '';
  loadCases();
}

function displayCases(cases) {
  const casesGrid = document.getElementById('casesGrid');
  casesGrid.innerHTML = '';

  if (cases && cases.length > 0) {
    cases.forEach(caseData => {
      const caseCard = createCaseCard(caseData);
      casesGrid.appendChild(caseCard);
    });
  } else {
    casesGrid.innerHTML = '<p style="text-align: center; color: #666; padding: 40px;">暂无案件数据</p>';
  }
}

function createCaseCard(caseData) {
  const template = document.getElementById('case-card-template');
  const cardElement = template.content.cloneNode(true);
  const cardContainer = cardElement.querySelector('.case-card');
  cardContainer.setAttribute('data-case-id', caseData.id);

  // 1. 头部信息
  const caseNameEl = cardElement.querySelector('.case-name');
  caseNameEl.textContent = caseData.case_name;

  // 锁图标
  const isEncrypted = caseData.password && caseData.password.trim() !== '';
  if (isEncrypted) {
    const lockIcon = cardElement.querySelector('.lock-icon');
    if (lockIcon) lockIcon.style.display = 'inline';
  }

  // 状态标签
  const statusTag = cardElement.querySelector('.status-tag');
  statusTag.textContent = caseData.case_status;
  statusTag.setAttribute('data-status', caseData.case_status);

  // 结案标签
  const isClosed = caseData.closed_status === 1;
  const closedBadge = cardElement.querySelector('.closed-badge');
  if (closedBadge) {
    closedBadge.style.display = isClosed ? 'inline-block' : 'none';
  }

  // 2. 主体信息
  cardElement.querySelector('.case-number').textContent = caseData.case_number || '无编号';

  // 时间显示 - 只使用立案时间（case_start_time）
  const timeStr = caseData.case_start_time;
  // 如果有立案时间，则使用它；否则显示"未设置"
  if (timeStr) {
    // 提取日期部分（年-月-日格式）
    const datePart = new Date(timeStr).toLocaleDateString('zh-CN');
    cardElement.querySelector('.created-time').textContent = datePart;
  } else {
    cardElement.querySelector('.created-time').textContent = '未设置';
  }

  // 添加案件描述信息
  const cardBody = cardElement.querySelector('.card-body');
  if (caseData.description) {
    const descriptionRow = document.createElement('div');
    descriptionRow.className = 'info-row description-row';
    descriptionRow.innerHTML = `
      <div class="label">案情简介：</div>
      <div class="value description-value" style="flex: 1; display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical; overflow: hidden; text-overflow: ellipsis; line-height: 1.4; cursor: pointer;"
           title="${caseData.description}">
        ${caseData.description}
      </div>
    `;
    cardBody.appendChild(descriptionRow);

    // 添加悬停显示全部内容的功能
    const descriptionValue = descriptionRow.querySelector('.description-value');
    descriptionValue.addEventListener('mouseenter', function() {
      if (this.scrollHeight > this.clientHeight) {
        // 创建悬停提示框
        const tooltip = document.createElement('div');
        tooltip.className = 'description-tooltip';
        tooltip.style.cssText = `
          position: absolute;
          background: white;
          border: 1px solid #dcdfe6;
          border-radius: 4px;
          padding: 12px;
          box-shadow: 0 4px 12px rgba(0,0,0,0.15);
          z-index: 10000;
          max-width: 300px;
          word-wrap: break-word;
          font-size: 14px;
          line-height: 1.5;
          color: #303133;
          white-space: pre-wrap;
        `;
        tooltip.textContent = caseData.description;

        // 定位悬停提示框在卡片上方
        const rect = this.getBoundingClientRect();
        tooltip.style.left = rect.left + 'px';
        tooltip.style.top = (rect.top - tooltip.offsetHeight - 10) + 'px';
        tooltip.style.maxHeight = '200px';
        tooltip.style.overflowY = 'auto';

        document.body.appendChild(tooltip);

        // 保存tooltip引用，以便在mouseleave时移除
        this._tooltip = tooltip;
      }
    });

    descriptionValue.addEventListener('mouseleave', function() {
      if (this._tooltip) {
        document.body.removeChild(this._tooltip);
        this._tooltip = null;
      }
    });
  }

  // 3. 动态生成"更多"菜单
  const dropdownMenu = cardElement.querySelector('.dropdown-menu');

  // 根据案件状态构建菜单项
  const menuItems = [];

  if (isEncrypted) {
    // 加密状态：修改密码、清除密码、导出数据、结案/取消结案、数据分析报告
    menuItems.push({ icon: '🔑', text: '修改密码', className: 'modify-password-btn' });
    menuItems.push({ icon: '🔓', text: '清除密码', className: 'clear-password-btn' });
  } else {
    // 未加密状态：案件加密、导出数据、结案/取消结案、数据分析报告
    menuItems.push({ icon: '🔒', text: '案件加密', className: 'set-password-btn' });
  }

  menuItems.push({ icon: '📤', text: '导出数据', className: 'export-btn' });

  if (isClosed) {
    menuItems.push({ icon: '📂', text: '取消结案', className: 'unclose-btn' });
  } else {
    menuItems.push({ icon: '✅', text: '结案', className: 'close-btn' });
  }

  menuItems.push({ icon: '📊', text: '数据分析报告', className: 'report-btn' });

  // 生成菜单HTML
  menuItems.forEach(item => {
    const btn = document.createElement('button');
    btn.className = `dropdown-item ${item.className}`;
    btn.innerHTML = `<span style="margin-right: 8px;">${item.icon}</span>${item.text}`;
    dropdownMenu.appendChild(btn);
  });

  return cardElement;
}

// 格式化日期
function formatDate(dateString) {
  const date = new Date(dateString);
  if (isNaN(date.getTime())) return dateString;
  return date.toLocaleString('zh-CN');
}

// ========== 事件委托 (交互核心优化版) ==========

let hoverTimer = null; // 全局定时器
let activeCard = null; // 记录当前激活的卡片

// 辅助函数：关闭所有菜单并恢复卡片层级
function closeAllDropdowns() {
  const openMenus = document.querySelectorAll('.dropdown-menu.show');
  openMenus.forEach(menu => {
    menu.classList.remove('show');
    menu.style.display = 'none';
  });

  // 关键：恢复之前被提高层级的卡片
  if (activeCard) {
    activeCard.style.zIndex = ''; // 清除内联 z-index，恢复 CSS 默认
    activeCard.style.position = ''; // 恢复定位
    activeCard = null;
  }
}

function setupCardEventDelegation() {
  const casesGrid = document.getElementById('casesGrid');
  if (!casesGrid) return;

  // 1. 鼠标移入事件 (处理显示)
  casesGrid.addEventListener('mouseover', function (e) {
    const target = e.target;

    // 情况A：移入了"更多"按钮
    const moreBtn = target.closest('.more-btn');
    if (moreBtn) {
      // 清除关闭定时器，防止误关
      if (hoverTimer) {
        clearTimeout(hoverTimer);
        hoverTimer = null;
      }

      const dropdown = moreBtn.closest('.dropdown');
      const dropdownMenu = dropdown.querySelector('.dropdown-menu');

      // 如果菜单还没显示，就显示出来
      if (!dropdownMenu.classList.contains('show')) {
        closeAllDropdowns(); // 关掉其他的
        showDropdownMenu(dropdown, dropdownMenu);
      }
      return;
    }

    // 情况B：移入了"菜单本身" (防止鼠标在移动菜单过程中菜单消失)
    const menu = target.closest('.dropdown-menu');
    if (menu && menu.classList.contains('show')) {
      // 只要鼠标在菜单上，就清除定时器，保持显示
      if (hoverTimer) {
        clearTimeout(hoverTimer);
        hoverTimer = null;
      }
    }
  });

  // 2. 鼠标移出事件 (处理延迟关闭)
  casesGrid.addEventListener('mouseout', function (e) {
    // 只有当移出的是"更多按钮"或者"菜单本身"时，才触发关闭倒计时
    const isLeavingBtn = e.target.closest('.more-btn');
    const isLeavingMenu = e.target.closest('.dropdown-menu');

    if (isLeavingBtn || isLeavingMenu) {
      // 重新设置定时器
      if (hoverTimer) clearTimeout(hoverTimer);

      // 设置 500ms 延迟，给用户足够的时间移动鼠标
      hoverTimer = setTimeout(() => {
        closeAllDropdowns();
      }, 500);
    }
  });

  // 3. 页面滚动时关闭 (保持交互整洁)
  window.addEventListener('scroll', closeAllDropdowns, true);

  // 4. 点击事件 (原有逻辑保持不变，只需增加关闭菜单调用)
  casesGrid.addEventListener('click', function (e) {
    const target = e.target;

    // 点击了菜单项后，立即关闭
    if (target.closest('.dropdown-item')) {
      closeAllDropdowns();
    }

    const card = target.closest('.case-card');
    if (!card) return;
    const caseId = parseInt(card.dataset.caseId);
    if (!caseId) return;

    // ... 原有按钮逻辑 ...
    if (target.closest('.edit-btn')) {
      e.preventDefault();
      getCaseById(caseId).then(caseData => {
        if (caseData) showEditCaseModal(caseData);
      });
      return;
    }

    const dropdownItem = target.closest('.dropdown-item');
    if (dropdownItem) {
      e.preventDefault();
      const className = dropdownItem.className;
      // ... 原有菜单点击逻辑 ...
      if (/\bset-password-btn\b/.test(className)) handleSetEncryption(caseId);
      else if (/\bmodify-password-btn\b/.test(className)) handleUpdatePassword(caseId);
      else if (/\bclear-password-btn\b/.test(className)) handleRemoveEncryption(caseId);
      else if (/\bclose-btn\b/.test(className)) handleCloseCase(caseId);
      else if (/\bunclose-btn\b/.test(className)) handleUncloseCase(caseId);
      else if (/\bexport-btn\b/.test(className)) showExportCaseModal(caseId);
      else if (/\breport-btn\b/.test(className)) alert('数据分析报告功能开发中...');
      return;
    }
    // ... 其他按钮逻辑 ...
    if (target.closest('.import-btn')) {
      e.preventDefault();
      handleImportClick(caseId);
    }
    if (target.closest('.analyze-btn')) {
      e.preventDefault();
      handleAnalyzeClick(caseId);
    }
    if (target.closest('.delete-btn')) {
      e.preventDefault();
      handleDeleteCase(caseId);
    }
  });
}

// 辅助函数：显示下拉菜单 (解决遮挡问题的关键版)
function showDropdownMenu(dropdown, dropdownMenu) {
  // 1. 解决遮挡问题的核心：提高整个卡片的层级
  const card = dropdown.closest('.case-card');
  if (card) {
    activeCard = card; // 记录下来以便稍后恢复
    // 将卡片层级设得非常高，确保它盖住后面的卡片
    card.style.zIndex = '1000';
    // 部分浏览器可能需要 relative 才能让 z-index 生效
    if (getComputedStyle(card).position === 'static') {
      card.style.position = 'relative';
    }
  }

  // 2. 初始化显示
  dropdownMenu.style.display = 'block';
  dropdownMenu.style.visibility = 'hidden';
  dropdownMenu.style.position = 'fixed'; // 保持 fixed 定位
  dropdownMenu.style.zIndex = '2000'; // 菜单比卡片更高

  // 3. 计算位置
  const moreBtn = dropdown.querySelector('.more-btn');
  const btnRect = moreBtn.getBoundingClientRect();

  const menuWidth = dropdownMenu.offsetWidth;
  const menuHeight = dropdownMenu.offsetHeight;
  const windowWidth = window.innerWidth;
  const windowHeight = window.innerHeight;

  // 4. 计算 Top
  let topPos = btnRect.bottom; // 紧贴按钮下方，去除间隙方便鼠标移动

  // 底部空间检查
  if (topPos + menuHeight > windowHeight) {
    if (btnRect.top > menuHeight) {
      topPos = btnRect.top - menuHeight; // 翻转到上方
    } else {
      topPos = windowHeight - menuHeight - 10; // 贴底
    }
  }

  // 5. 计算 Left
  let leftPos = btnRect.left;

  // 右侧边界检查
  if (leftPos + menuWidth > windowWidth) {
    leftPos = btnRect.right - menuWidth;
  }
  if (leftPos < 5) leftPos = 5;

  // 6. 应用样式
  dropdownMenu.style.top = topPos + 'px';
  dropdownMenu.style.left = leftPos + 'px';
  dropdownMenu.style.visibility = 'visible';
  dropdownMenu.classList.add('show');
}

// 获取案件详细信息
async function getCaseById(caseId) {
  try {
    const cases = await window.electronAPI.case.getAll();
    return cases.find(caseItem => caseItem.id === caseId);
  } catch (error) {
    console.error('获取案件详情失败:', error);
    return null;
  }
}

// ========== 业务逻辑函数 (之前缺失的部分) ==========

// 显示导出案件对话框
function showExportCaseModal(caseId) {
  const modal = document.getElementById('exportCaseModal');
  if (modal) {
    document.getElementById('exportCaseId').value = caseId;
    document.getElementById('exportPath').value = '';
    document.getElementById('exporterName').value = '';
    document.getElementById('encryptPackage').checked = false;
    document.getElementById('passwordGroup').style.display = 'none';
    modal.style.display = 'flex';
  }
}

// 显示导入案件对话框
function showImportCaseModal() {
  const modal = document.getElementById('importCaseModal');
  if (modal) {
    document.getElementById('importFilePath').value = '';
    document.getElementById('ignoreIntegrity').checked = false;
    document.getElementById('decryptPassword').value = '';
    modal.style.display = 'flex';
  }
}

// 选择导出路径
async function selectExportPath() {
  const result = await window.electronAPI.file.selectExportPath();
  if (result) {
    document.getElementById('exportPath').value = result;
  }
}

// 选择导入文件
async function selectImportFile() {
  const result = await window.electronAPI.file.selectImportFile();
  if (result) {
    document.getElementById('importFilePath').value = result;
  }
}

// 处理导出表单提交
async function handleExportSubmit(event) {
  event.preventDefault();

  const caseId = document.getElementById('exportCaseId').value;
  const formData = {
    exportPath: document.getElementById('exportPath').value,
    exporter: document.getElementById('exporterName').value,
    encryptPackage: document.getElementById('encryptPackage').checked,
    password: document.getElementById('packagePassword').value
  };

  if (!formData.exportPath) {
    alert('请选择导出路径');
    return;
  }

  try {
    const result = await window.electronAPI.case.export(parseInt(caseId), formData);
    if (result.success) {
      alert(`案件导出成功！文件位置：${result.filePath}`);
      hideExportCaseModal();
    }
  } catch (error) {
    alert(`导出失败：${error.message}`);
  }
}

// 处理导入表单提交
async function handleImportSubmit(event) {
  event.preventDefault();

  const formData = {
    importFilePath: document.getElementById('importFilePath').value,
    ignoreIntegrity: document.getElementById('ignoreIntegrity').checked,
    decryptPassword: document.getElementById('decryptPassword').value
  };

  if (!formData.importFilePath) {
    alert('请选择要导入的案件文件');
    return;
  }

  try {
    const result = await window.electronAPI.case.import(formData.importFilePath, formData);
    if (result.success) {
      alert(`案件导入成功！案件名称：${result.caseName}`);
      hideImportCaseModal();
      loadCases(); // 重新加载案件列表
    }
  } catch (error) {
    alert(`导入失败：${error.message}`);
  }
}

// 加密选项切换
function togglePasswordGroup() {
  const encryptPackage = document.getElementById('encryptPackage');
  const passwordGroup = document.getElementById('passwordGroup');
  passwordGroup.style.display = encryptPackage.checked ? 'block' : 'none';
}

// 隐藏导出对话框
function hideExportCaseModal() {
  const modal = document.getElementById('exportCaseModal');
  if (modal) {
    modal.style.display = 'none';
  }
}

// 隐藏导入对话框
function hideImportCaseModal() {
  const modal = document.getElementById('importCaseModal');
  if (modal) {
    modal.style.display = 'none';
  }
}


// 处理分析按钮点击 - 跳转到智能分析模块
async function handleAnalyzeClick(caseId) {
  try {
    const caseData = await getCaseById(caseId);
    if (caseData) {
      // 跳转到工作台并激活智能分析标签，同时传递案件信息
      window.electronAPI.navigation.openWorkbench({
        activeTab: 'analysis',
        caseId: caseId,
        caseName: caseData.case_name
      });
    } else {
      alert('无法获取案件信息');
    }
  } catch (error) {
    console.error('打开智能分析失败:', error);
    alert('打开智能分析失败，请重试');
  }
}


// 5. 结案
async function handleCloseCase(caseId) {
  try {
    const caseData = await getCaseById(caseId);
    if (caseData) {
      if (confirm(`确定要结案"${caseData.case_name}"吗？`)) {
        const result = await window.electronAPI.case.update({
          id: caseData.id,
          closed_status: 1
        });
        if (result && result.changes > 0) {
          loadCases();
        } else {
          alert('结案失败，请重试');
        }
      }
    }
  } catch (error) {
    console.error('结案操作失败:', error);
    alert(`结案失败: ${error.message}`);
  }
}

// 6. 取消结案
async function handleUncloseCase(caseId) {
  try {
    const caseData = await getCaseById(caseId);
    if (caseData) {
      if (confirm(`确定要取消结案"${caseData.case_name}"吗？`)) {
        const result = await window.electronAPI.case.update({
          id: caseData.id,
          closed_status: 0
        });
        if (result && result.changes > 0) {
          loadCases();
        } else {
          alert('取消结案失败，请重试');
        }
      }
    }
  } catch (error) {
    console.error('取消结案操作失败:', error);
    alert(`取消结案失败: ${error.message}`);
  }
}

// 删除案件
async function handleDeleteCase(caseId) {
  try {
    const caseData = await getCaseById(caseId);
    if (caseData) {
      const confirmed = confirm(`确定要删除案件"${caseData.case_name}"吗？\n注意：此操作不可撤销！\n\n案件编号: ${caseData.case_number}\n案件状态: ${caseData.case_status}\n创建时间: ${formatDate(caseData.created_time)}`);
      if (confirmed) {
        const result = await window.electronAPI.case.delete(caseId);
        if (result && result.changes > 0) {
          loadCases(); // 重新加载案件列表
          alert('案件删除成功！');
        } else {
          alert('案件删除失败，请重试');
        }
      }
    }
  } catch (error) {
    console.error('删除案件失败:', error);
    alert(`删除案件失败: ${error.message}`);
  }
}

// 导入点击 - 跳转到工作台
function handleImportClick(caseId) {
  getCaseById(caseId).then(caseData => {
    if (caseData) {
      if (caseData.closed_status === 1) {
        alert('案件已结案，无法导入');
      } else {
        // 保存当前案件ID到会话存储或通过URL参数传递给工作台
        sessionStorage.setItem('currentCaseId', caseId);
        sessionStorage.setItem('currentCaseName', caseData.case_name);
        // 跳转到工作台页面
        window.location.href = 'pages/workbench.html';
      }
    }
  });
}

// ========== 密码模态框相关功能 ==========

// 绑定密码模态框事件
function bindPasswordModalEvents() {
  const closeBtn = document.getElementById('closePasswordModal');
  const cancelBtn = document.getElementById('cancelPassword');
  const passwordForm = document.getElementById('passwordForm');
  const modalOverlay = document.getElementById('setPasswordModal');

  if (closeBtn) {
    closeBtn.addEventListener('click', hidePasswordModal);
  }

  if (cancelBtn) {
    cancelBtn.addEventListener('click', hidePasswordModal);
  }

  if (modalOverlay) {
    modalOverlay.addEventListener('click', function (e) {
      if (e.target === modalOverlay) {
        hidePasswordModal();
      }
    });
  }

  if (passwordForm) {
    passwordForm.addEventListener('submit', handlePasswordSubmit);
  }
}

// 显示密码模态框
function showPasswordModal(operation, caseData) {
  const modal = document.getElementById('setPasswordModal');
  const title = document.getElementById('passwordModalTitle');
  const caseIdInput = document.getElementById('passwordCaseId');
  const operationInput = document.getElementById('passwordOperation');
  const currentPasswordGroup = document.getElementById('currentPasswordGroup');
  const passwordHint = document.getElementById('passwordHint');
  const newPasswordInput = document.getElementById('newPassword');
  const confirmPasswordInput = document.getElementById('confirmPassword');
  const currentPasswordInput = document.getElementById('currentPassword');

  if (modal) {
    // 重置表单
    document.getElementById('passwordForm').reset();

    // 设置操作类型
    operationInput.value = operation;
    caseIdInput.value = caseData.id;

    // 根据操作类型设置标题和界面
    switch (operation) {
      case 'set':
        title.textContent = `为 "${caseData.case_name}" 设置密码`;
        currentPasswordGroup.style.display = 'none';
        passwordHint.style.display = 'none';
        break;
      case 'update':
        title.textContent = `修改 "${caseData.case_name}" 的密码`;
        currentPasswordGroup.style.display = 'block';
        passwordHint.style.display = 'none';
        break;
      case 'remove':
        title.textContent = `取消 "${caseData.case_name}" 的加密`;
        currentPasswordGroup.style.display = 'block';
        passwordHint.style.display = 'block';
        // 对于取消加密，新密码字段可以为空
        newPasswordInput.placeholder = "留空以取消加密";
        confirmPasswordInput.placeholder = "留空以取消加密";
        break;
    }

    modal.style.display = 'flex';

    // 聚焦到第一个需要输入的字段
    setTimeout(() => {
      if (operation === 'set' || operation === 'update') {
        currentPasswordInput.focus();
      } else {
        newPasswordInput.focus();
      }
    }, 100);
  }
}

// 隐藏密码模态框
function hidePasswordModal() {
  const modal = document.getElementById('setPasswordModal');
  if (modal) {
    modal.style.display = 'none';
    // 重置表单
    document.getElementById('passwordForm').reset();
  }
}

// 处理密码表单提交
async function handlePasswordSubmit(event) {
  event.preventDefault();

  const operation = document.getElementById('passwordOperation').value;
  const caseId = parseInt(document.getElementById('passwordCaseId').value);
  const currentPassword = document.getElementById('currentPassword').value;
  const newPassword = document.getElementById('newPassword').value;
  const confirmPassword = document.getElementById('confirmPassword').value;
  const saveBtn = document.querySelector('#setPasswordModal .btn-save');

  if (saveBtn.disabled) return;

  try {
    // 验证密码
    if (operation !== 'remove' && newPassword !== confirmPassword) {
      alert('两次输入的密码不一致，请重新输入！');
      return;
    }

    if (operation !== 'remove' && newPassword.trim() === '') {
      alert('密码不能为空！');
      return;
    }

    // 对于修改密码或取消加密，需要验证当前密码
    if (operation === 'update' || operation === 'remove') {
      const caseData = await getCaseById(caseId);
      if (caseData.password !== currentPassword) {
        alert('当前密码错误，无法继续操作。');
        return;
      }
    }

    // 准备要发送的密码值
    let passwordToSend = newPassword;
    if (operation === 'remove') {
      // 对于取消加密，如果新密码为空，则发送null
      passwordToSend = newPassword.trim() === '' ? null : newPassword;
    }

    // 执行密码操作
    const originalText = saveBtn.textContent;
    saveBtn.textContent = '处理中...';
    saveBtn.disabled = true;

    const result = await window.electronAPI.case.update({
      id: caseId,
      password: passwordToSend
    });

    if (result && result.changes > 0) {
      saveBtn.textContent = '成功！';
      setTimeout(() => {
        hidePasswordModal();
        loadCases();
        saveBtn.textContent = originalText;
        saveBtn.disabled = false;
      }, 500);
    } else {
      alert('操作失败，请重试');
      saveBtn.textContent = originalText;
      saveBtn.disabled = false;
    }
  } catch (error) {
    console.error('密码操作失败:', error);
    alert(`操作失败: ${error.message}`);
    if (saveBtn) {
      saveBtn.textContent = '确认';
      saveBtn.disabled = false;
    }
  }
}

// 更新设置加密函数 - 使用模态框
function handleSetEncryption(caseId) {
  getCaseById(caseId).then(caseData => {
    if (caseData) {
      showPasswordModal('set', caseData);
    }
  });
}

// 更新修改密码函数 - 使用模态框
function handleUpdatePassword(caseId) {
  getCaseById(caseId).then(caseData => {
    if (caseData) {
      showPasswordModal('update', caseData);
    }
  });
}

// 更新移除加密函数 - 使用模态框
function handleRemoveEncryption(caseId) {
  getCaseById(caseId).then(caseData => {
    if (caseData) {
      showPasswordModal('remove', caseData);
    }
  });
}